<template>
  <!-- AttendanceCard 参会证 -->
  <PageContainer>
    <view class="container">
      <Header title="参会证" />
      <image :src="imgUrl" mode="widthFix" @click="previewImage" />

      <TButtonGroup>
        <TButton
          v-if="isActivityArrange"
          class="gutter-btn"
          text="查看活动安排及排座"
          type="none"
          custom-class="borderBtn"
          @click="toScheduling"
        />
        <TButton class="gutter-btn" text="保存图片" type="primary" @click="submit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  AttendanceCard  参会证 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateTo, onLoad } from '@/router';
  import { ref, unref } from 'vue';
  import { attendanceCard } from '@/api/activity';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { defHttp } from '@/utils/http';

  const activityId = ref<number>(Infinity);
  const activityRegisterId = ref<number>(Infinity);
  const isActivityArrange = ref<boolean>(false);
  const imgUrl = ref<string>('');

  onLoad<'AttendanceCard'>((op) => {
    activityId.value = op.activityId;
    if (op.attendanceCardUrl) {
      imgUrl.value = op.attendanceCardUrl;
      activityRegisterId.value = op.activityRegisterId as number;
      isActivityArrange.value = op.isActivityArrange as boolean;
    } else {
      attendanceCard(op.activityId, op.url, op.equipmentNumber).then((r) => {
        imgUrl.value = r.attendanceCardUrl;
        activityRegisterId.value = r.activityRegisterId;
        isActivityArrange.value = r.isActivityArrange;
        // base64ToPath(r).then((url) => (imgUrl.value = url));
      });
    }
  });

  function toScheduling() {
    navigateTo({
      name: 'activityScheduling',
      options: { activityId: unref(activityId), activityRegisterId: unref(activityRegisterId) },
    });
  }

  const localUrl = ref<string>();
  /** 保存参会证 */
  async function submit() {
    let path = localUrl.value || '';
    if (!localUrl.value) path = await defHttp.download(imgUrl.value);
    wx.showShareImageMenu({
      path,
      fail: (err) => {
        console.log(err);
      },
    });
  }

  /** 预览参会证 */
  function previewImage() {
    uni.previewImage({ urls: [imgUrl.value] });
  }
</script>

<style lang="scss" scoped>
  .container {
    display: flex;
    flex-direction: column;
    > image {
      width: 100%;
    }
  }
</style>
